<template>
  <div class="searchCon white_bg">
    <div :class="scrollClass?'searchTop_fixed':'searchTop'" class="white_bg" id="searchTop">
      <!-- 添加按钮-->
      <div class="addBtnCon white_bg">
        <div class="addBtn" @click="left_bar_switch" v-if="!searchPage">
          <i class="icon iconfont icon-tianjia" ref="icon"></i>
        </div>
        <!-- 取消按钮-->
        <div class="close_search white_bg" @click="hide_page" v-else>
          取消
        </div>
      </div>
      <div class="s_inputCon">
        <div class="selectCon" @click="show = !show">
          <div class="selectSite">
            <p>{{checked}}</p>
            <transition enter-active-class="bounceDown" leave-active-class="bounce" v-if="show && types.length>1">
              <!-- 选择类型-->
              <ul>
                <li @click.stop="selectType(item.key)" v-for="(item, index) in types" :key="index">
                  {{item.name}}
                </li>
              </ul>
            </transition>
          </div>
          <!--<i class="icon iconfont icon-down downIcon" :class="{rotate:show}"></i>-->
        </div>
        <!-- 输入框-->
        <form action="#" class="searchInput" @submit.prevent="searchEvent" @click="show_page">
          <input type="text" class="searchInput2" v-model.trim="searchKey" :placeholder="fontConent" @focus="focuss"
                 @blur="blurr" ref='searchBox' v-if="type === 'mecth'" maxlength="15">
          <input type="text" class="searchInput2" v-model.trim="searchKey" :placeholder="fontConent" @focus="focuss"
                 @blur="blurr" ref='searchBox' v-else="type === 'coupon'" maxlength="15">
        </form>
        <!-- 搜索按钮-->
        <span class="searchBtnCon" @click="searchEvent"><i class="icon iconfont icon-sou searchBtn"></i></span>
        <!-- 右侧滑动导航-->
        <transition enter-active-class="slideInRight" leave-active-class="slideOutRight">
          <div class="leftBarCon white_bg" v-show="leftBar">
            <ul>
              <li v-for="(item,index) in functions" :key="index" @click="funClick(item.type)">
                <div class="fun_icon"><i class="iconfont" :class="item.icon"></i></div>
                <p>{{item.name}}</p>
              </li>
            </ul>
          </div>
        </transition>
      </div>
    </div>

    <div class="searchPage" v-if="searchPage" id="searchCon">
      <!-- 发现栏 -->
      <div class="findCon">
        <div class="search_tit2">
          <span class="event_btn" @click="getNewTag">换一组</span>
          <span class="">你可能在找</span>
        </div>
        <div class="find_list" v-if="tagList.length !=0">
          <ul>
            <li v-for="item in tagList" @click="searchTag(item.des)" class="white_bg">{{item.des}}</li>
          </ul>
        </div>
      </div>
      <!--搜索历史 -->
      <div class="historyCon" v-if="historyTab">
        <div class="search_tit white_bg">
          <span class="event_btn" @click="clearHistory">清除</span>
          <span>搜索历史</span>
        </div>
        <ul class="history_list">
          <!-- 电子券 -->
          <li v-for="(item, index) in historyList" @click="searchHistory(item)"
              v-if="searchType === 'coupon' && item.type == 'coupon' && item.info!=''" :key="index" class="white_bg">
          <span class="list_icon">
            <icon iconName="#icon-lishidianziquan-"></icon>
          </span>
            <a href="javascript:;">{{item && item.info}}</a>
          </li>
          <!-- 商户 -->
          <li v-for="(item, index) in historyList" @click="searchHistory(item)"
              v-if="searchType === 'mecth' && item.type == 'mecth' && item.info!=''" :key="index" class="white_bg">
          <span class="list_icon">
            <icon iconName="#icon-lishishanghu-" otherClass="list_icon"></icon>
          </span>
            <a href="javascript:;">{{item && item.info}}</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
    import {mapState} from 'vuex'
    import {Toast, Indicator} from 'mint-ui'
    import getData from '../../service/getData.js'
    import * as types from '../../vuex/types.js'
    import SearchBarView from 'src/componentes/global/search_bar.vue'
    import {Storage} from 'src/utils/storage.js'

    export default {
        name: "search-bar",
        components: {SearchBarView},
        data() {
            return {
                fontConent: "请输入商户名称",
                show: false,
                leftBar: false,
                searchPage: false,
                showPage: '',
                functions: [
                    {icon: 'icon-RichScan', name: '扫一扫', type: 'scan'},
                    {icon: 'icon-user-code', name: '账户码', type: 'code'},
                    {icon: 'icon-ticket-bag', name: '商券', type: 'ticket'},
                    {icon: 'icon-message-copy', name: '消息', type: 'message'}
                ],
                types: [
                    {key: 'mecth', name: '商户'},
                    {key: 'coupon', name: '电子券'}
                ],
                type: '',
                tagList: [],
                searchKey: '',
                historyTab: false,
                isChooCity: false,
                scrollClass: false,
            }
        },
        computed: {
            ...mapState({
                userInfo: state => state.user.userInfo, //用户信息
                historyList: state => state.coupon.historyList, // 搜索关键字
                searchType: state => state.coupon.searchType, // 搜索类型
                keyWord: state => state.coupon.searchKey // 搜索类型
            }),
            checked() {
                let val;
                if (this.showCity) {
                    val = this.checkedCity
                } else {
                    let types = this.types.find(item => item.key === this.searchType); // 根据搜索类型取得搜索项
                    this.types = types; // 赋值搜索项，mecth和coupon只会留对象选项下来，不准点击下拉选择
                    console.log(types)
                    val = types.name // 显示搜索类名
                }
                return val
            }
        },
        props: {
            'checkedCity': {
                type: String,
                default: ''
            },
            'showCity': {
                type: Boolean,
                default: false
            }
        },
        created: function () {
            window.addEventListener('scroll', this.handleScroll);
            //解决ios返回出现空白问题
            setTimeout(function () {
                window.scrollTo(0, 1);
                window.scrollTo(0, 0);
            }, 100);
            this.historyTab = !!Storage.get("history_info");
            var randomNum;
            if (!Storage.get("tag", true) || Storage.get("tag", true).length == 0) {
                getData.tagList().then(rep => {
                    if (rep.content.length != 0) {
                        Storage.set("tag", rep.content, true);
                        randomNum = rep.content.length >= 8 ? 8 : rep.content.length
                        this.tagList = this.randomArray(rep.content, randomNum);
                    }
                })
            } else {
                randomNum = Storage.get("tag", true).length >= 8 ? 8 : Storage.get("tag", true).length
                this.tagList = this.randomArray(Storage.get("tag", true), randomNum);
            }
        },
        mounted() {
            let router = this.$route.query
            if (router.type === 'home') {
                this.searchPage = true
            }
            //加载缓存是搜索商户还是电子券
            if (this.searchType) {
                this.searchKey = '';
                this.$store.commit("search_type", this.searchType);
                if (this.searchType === 'coupon') {
                    this.fontConent = "请输入电子券名称";
                } else {
                    this.fontConent = "请输入商户名称";
                }
            }
        },
        methods: {
            handleScroll() {
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                if (scrollTop >= 40) {
                    this.scrollClass = true;
                } else {
                    this.scrollClass = false;
                }
            },
            funClick(type) {
                if (type === 'scan') {
                    this.scan()
                } else if (type === 'code') {
                    this.$router.push({
                        name: 'changeUserInfo',
                        params: {infoType: 'code'}
                    })
                } else if (type === 'ticket') {
                    this.$router.push({path: '/cardList', query: {jump: 1}})
                } else if (type === 'message') {
                    this.$router.push({
                        name: 'infoList'
                    })
                }
            },
            selectType: function (type) {
                this.searchKey = '';
                this.$nextTick(() => {
                    this.show = false
                });
                this.type = type
                this.blurr()
                this.$store.commit("search_type", type);
                this.$store.commit("search_key", this.searchKey);
                this.show_page();
            },
            focuss: function () {
                this.fontConent = "";
                this.show = false
            },
            blurr: function () {
                if (this.searchType === 'coupon') {
                    this.fontConent = "请输入电子券名称";
                } else {
                    this.fontConent = "请输入商户名称";
                }
            },
            show_page: function () {
                this.searchKey = "";
                this.searchPage = true;
                // this.show = false;
                if (Storage.get("history_info")) {
                    this.historyTab = true;
                } else {
                    this.historyTab = false;
                }
                this.$emit('hidden-view', false);
            },
            hide_page() {

                let router = this.$route.query
                if (router.type === 'home') {
                    this.$router.back()
                } else {
                    this.searchKey = ''
                    this.$store.commit("search_key", this.searchKey);
                    this.searchEvent();
                    this.show = false
                    this.searchPage = false
                    this.$emit('hidden-view', true)
                }
            },
            left_bar_switch: function () {
                this.leftBar = this.leftBar ? false : true;
                this.show = false;
                if (this.leftBar) {
                    this.$refs.icon.className = 'icon iconfont icon-tianjia addIcon'
                } else {
                    this.$refs.icon.className = 'icon iconfont icon-tianjia removeIcon'
                }
            },
            searchHistory: function (item) { //点击搜索历史
                this.searchKey = item.info;
                this.$store.commit("search_key", item.info);
                this.$store.commit("search_type", item.type);
                this.searchEvent();
            },
            searchTag: function (key) { //点击标签
                this.searchKey = key;
                this.$store.commit("search_key", key);
                this.searchEvent();
            },
            searchEvent: function () {
                if (!this.searchKey) {
//    	return
                }
                this.$store.commit(types.GET_PAGE_NUM, 1)
                this.$store.commit("search_key", this.searchKey);
                this.$store.commit("search_type", this.searchType); //设置搜索类型//cop、mer
                this.addSearchInfo(); //添加搜索历史
                let router = this.$route.query
                if (router.type === 'home') {
                    Storage.set("menuArr", Storage.get('menu', true), true);
                    this.$store.commit(types.coupon_tit, '全部')
                    this.$router.push({
                        name: 'couponSearch',
                        query: {type: true}
                    })
                } else {
                    this.searchPage = false
                    this.$store.commit(types.coupon_tit, '全部')
                    this.$emit('click-search')
                }
            },
            scan: function () {
                let me = this;
                new Promise((resolve, reject) => {
                    wx.scanQRCode({
                        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                        success: function (res) {
                            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果

                            resolve(result);
                        }
                    });
                }).then(rep => {
                    let obj = JSON.parse(rep.substr(rep.indexOf("V=") + 2, rep.length - 1));
//          let obj_scene= rep.substr(rep.indexOf("sc="), 5)
                    let queryObject = {};
                    if (rep.indexOf('?') >= 0) {
                        rep.split('?')[1].split('&').forEach(data => queryObject[data.split('=')[0]] = data.split('=')[1]); // 获取url上的每个参数集成在jumpPageObject对象
                    }

                    if (result.indexOf('payIndex') >= 0) {
                        // Indicator.open("订单查询中...");
                        me.$store.commit('changeState', true)
                        me.$router.push({
                            'path': '/payIndex',
                            query: queryObject
                        });
                    } else if (result.indexOf('positiveScan') >= 0) {
                        me.$router.push({
                            'name': 'positiveScan',
                            query: queryObject
                        });
                    } else if (obj.usrId) {
                        if (obj.usrId == me.userInfo.usrId) {
                            Toast({
                                message: "不能添加自己为好友",
                                duration: 800
                            });
                            return;
                        }
                        me.$store.commit(types.search_friend, {id: obj.usrId})
                        me.$router.push({
                            "path": '/addFriend'
                        })
                        //扫一扫圈友号二维码，加圈友，跳转圈友详情页面
                        getData.searchFriend({
                            method: 'post',
                            data: {
                                friendId: obj.usrId,
                                usrId: me.userInfo.usrId
                            }
                        }).then(function (rep) {
                            if (rep.respCode == '00') {
                                if (rep.content) {
                                    me.$store.commit("search_friend", rep.content);
                                    me.$router.push({
                                        "path": '/addFriend'
                                    })
                                } else {
                                    Toast({
                                        message: "用户不存在",
                                        duration: 800
                                    });
                                }
                            } else {
                                Toast({
                                    message: rep.errorInfo,
                                    duration: 800
                                });
                            }
                        })
                    } else {
                        Toast({
                            message: "二维码不正确",
                            duration: 800
                        });
                    }
                }).catch(error => {
                    Toast({
                        message: "二维码不正确",
                        duration: 800
                    })
                });
            },
            clearHistory: function () {

                //    Storage.remove("history_info");
                //    this.$store.commit("history_info", []); //设置搜索历史
                var newArray = Storage.get("history_info");
                var shuziArray = [];
                var i;
                newArray.find(function (item, index) {
                    if (item.type == "coupon") {
                        shuziArray.push(index);
                        i = shuziArray.length
                    }
                });

                if (this.searchType == "coupon") {
                    newArray.splice(0, i);
                    Storage.set("history_info", newArray); //保存至本地
                    this.$store.commit("history_info", newArray); //设置搜索历史
                } else {
                    newArray.splice(-(newArray.length - i));
                    Storage.set("history_info", newArray); //保存至本地
                    this.$store.commit("history_info", newArray); //设置搜索历史
                }


                Toast({
                    message: '操作成功',
                    duration: 1000
                });
                this.historyTab = false;
            },
            addSearchInfo: function () {
                let array = Storage.get("history_info") || [];
                let merchArr = [];
                let couponArr = [];
                array.forEach(item => {
                    if (item.type === 'mecth') {
                        merchArr.push(item)
                    } else if (item.type === 'coupon') {
                        couponArr.push(item)
                    }
                });
                // 判断是否重复
                let val = array.find(item => item.info === this.searchKey && item.type === this.searchType);
                if (this.searchType == 'coupon') {
                    couponArr.unshift({
                        type: 'coupon',
                        info: this.searchKey
                    });
                    if (couponArr.lastIndexOf(val) > 0) { //查找相同元素   放在第一位
                        couponArr.splice(couponArr.lastIndexOf(val), 1)
                    }
                    couponArr = couponArr.slice(0, 10)
                } else {
                    merchArr.unshift({
                        type: 'mecth',
                        info: this.searchKey
                    });
                    if (merchArr.lastIndexOf(val) > 0) { //查找相同元素   放在第一位
                        merchArr.splice(merchArr.lastIndexOf(val), 1)
                    }
                    merchArr = merchArr.slice(0, 10)
                }
                array = couponArr.concat(merchArr);
                Storage.set("history_info", array); //保存至本地
                this.$store.commit("history_info", array); //设置搜索历史
            },
            randomArray: function (arr, count) {
                var shuffled = arr.slice(0),
                    i = arr.length,
                    min = i - count,
                    temp, index;
                while (i-- > min) {
                    index = Math.floor((i + 1) * Math.random());
                    temp = shuffled[index];
                    shuffled[index] = shuffled[i];
                    shuffled[i] = temp;
                }
                return shuffled.slice(min);
            },
            getNewTag: function () {
                if (Storage.get("tag", true).length < 8) {
                    return;
                }
                this.tagList = this.randomArray(Storage.get("tag", true), 8);
            }
        },
        beforeRouteLeave(to, from, next) {
            window.removeEventListener('scroll', this.handleScroll);

            next()
        }
    }
</script>

<style scoped>
  .fun_icon i {
    font-size: 1.2rem;
  }

  .location {
    font-size: 1rem;
  }

  .city ul {
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 2.5rem;
    background: #eb4f89;
    width: 5rem;
    z-index: 5;
    border-bottom-left-radius: .2rem;
    border-bottom-right-radius: .2rem;
  }

  .searchCon {
    position: relative;
    height: 4.334rem;
    width: 100%;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    z-index: 111;
    -webkit-overflow-scrolling: touch;
  }

  .searchTop {
    position: static;
    left: 0;
    right: 0;
    top: 0;
    height: 4.5rem;
    padding: .667rem 0;
    z-index: 12;
  }

  .searchTop_fixed {
    left: 0;
    right: 0;
    top: 0;
    height: 3rem;
    padding: .667rem 0;
    z-index: 12;
    position: fixed;
    top: 0;
    left: 0;
  }

  /*整左侧*/

  .s_inputCon {
    height: 3rem;
    line-height: 3rem;
    position: absolute;
    z-index: 3;
    margin: 0 0 0 .667rem;
    width: -webkit-calc(100% - 5.1rem);
    /*display: flex;*/
  }

  .city {
    width: 5rem;
    height: 100%;
    background: #eb4f89;
    border-top-left-radius: .2rem;
    border-bottom-left-radius: .2rem;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    text-align: center;
    color: #fff;
    font-size: 1rem;
  }

  .selectCon {

    width: 23%;
    height: 100%;
    background: #eb4f89;
    border-top-left-radius: .2rem;
    border-bottom-left-radius: .2rem;
    float: left;
    position: relative;
  }

  .selectSite {
    padding: 0 .4rem;
    /*color:#f0cbd7;*/
    color: #fff;
    position: relative;
    float: left;
  }

  .selectCon ul {
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 2.5rem;
    background: #eb4f89;
    width: 5rem;
    z-index: 5;
    border-bottom-left-radius: .2rem;
    border-bottom-right-radius: .2rem;
  }

  .selectCon ul li {
    padding-left: .4rem;
  }

  .downIcon {
    color: #f0cbd7;
    margin-left: 0;
    font-size: 1rem;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 1;
  }

  .searchInput {
    height: 100%;
    float: left;
    /*flex: 1;*/
    width: 62%;
    color: #fff;
    background: -webkit-linear-gradient(to right, #eb4f89, #f85b7b);
    background: linear-gradient(to right, #eb4f89, #f85b7b);
    border-radius: 0;
  }

  .searchInput2 {
    width: 100%;
    height: 100%;
    text-indent: .4rem;
    font-size: 1rem;
    background: transparent;
    color: #fff;
  }

  .searchInput2::-webkit-input-placeholder {
    color: #fff;
  }

  .searchBtnCon {
    height: 3rem;
    width: 14%;
    line-height: 3.2rem;
    background: #f85b7b;
    float: left;
    border-top-right-radius: .2rem;
    border-bottom-right-radius: .2rem;
    text-align: center;
  }

  .searchBtn {
    color: #fff;
    font-size: 2rem;
  }

  .addBtnCon {
    padding: 0 .667rem 0 .667rem;
    position: relative;
    z-index: 5;
    float: right;
  }

  .addBtn {
    height: 3rem;
    width: 3rem;
    background: #f95a7c;
    border-radius: .2rem;
    line-height: 3rem;
    color: #fff;
    text-align: center;
    position: relative;
    z-index: 3;
  }

  .addBtn .icon {
    font-size: 2rem;
  }

  .leftBarCon {
    position: absolute;
    left: 0;
    width: -webkit-calc(100% - 0rem);
    /*background: #fff;*/
    top: 0;
    height: 100%;
    z-index: 2;
    background: linear-gradient(35deg, #eb4f89, #f85b7b);
    border-radius: .2rem;
  }

  .leftBarCon li {
    float: left;
    color: #fff;
    width: 25%;
    text-align: center;
    line-height: 2rem;
  }

  .leftBarCon li p {
    font-size: .8rem;
    line-height: .8rem;
  }

  .leftBarCon li .icon {
    font-size: 1.4rem;
    display: inline-block;
  }

  .leftBarCon li a {
    color: #fff;
  }

  .icon.addIcon {
    -webkit-animation: rotate_along .5s forwards;
    display: block;
  }

  .icon.removeIcon {
    -webkit-animation: rotate_inverse .5s forwards;
    display: block;
  }

  .search_right_box {
    overflow: hidden;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border-radius: .2rem;
  }

  @keyframes rotate_along {
    0% {
      -webkit-transform: rotate(0deg);
    }
    100% {
      -webkit-transform: rotate(-45deg);
    }
  }

  @keyframes rotate_inverse {
    0% {
      -webkit-transform: rotate(-45deg);
    }
    100% {
      -webkit-transform: rotate(0deg);
    }
  }

  .icon.rotate {
    -webkit-transform: rotate(180deg) !important;
    display: block;
  }

  /* 可以设置不同的进入和离开动画 */

  /* 设置持续时间和动画函数 */

  .bounce-enter-active {
    animation: bounce-in .5s;
  }

  .bounce-leave-active {
    animation: bounce-out .5s;
  }

  @keyframes bounce-in {
    0% {
      height: 0;
    }
    100% {
      height: 5.2rem;
    }
  }

  @keyframes bounce-out {
    0% {
      height: 5.2rem;
    }
    100% {
      height: 0;
    }
  }

  .searchPage {
    position: relative;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: #F5F5F5;
  }

  .findCon {
    overflow: hidden;
    margin-top: 0;
  }

  .find_list li {
    float: left;
    width: -webkit-calc((100% - 3.335rem) / 4);
    height: 2.2rem;
    line-height: 2.2rem;
    /*background: #fff;*/
    margin-left: .667rem;
    color: #333;
    margin-bottom: .667rem;
    text-align: center;
  }

  .search_tit {
    color: #999;
    padding: 0 .667rem;
    /*background: #fff;*/
    height: 3rem;
    line-height: 3rem;
  }

  .search_tit2 {
    color: #999;
    padding: 0 .667rem;
    height: 3rem;
    line-height: 3rem;
  }

  .historyCon {
    overflow: hidden;
  }

  .event_btn {
    float: right;
    color: #ED4F8A;
  }

  .history_list {
    overflow: hidden;
  }

  .history_list li {
    float: left;
    margin: .667rem 0 0 .667rem;
    line-height: 2.4rem;
    padding: 0 .4rem;
  }

  .history_list span.list_icon {
    float: left;
    font-size: 1.6rem;
    margin-right: .4rem;
  }

  .history_list a {
    color: #969696;
    font-size: 1rem;
  }

  .close_search {
    width: 3rem;
    height: 3rem;
    line-height: 3rem;
    position: absolute;
    z-index: 5;
    right: .667rem;
    color: #666666;
    /*background: #fff;*/
    text-align: center;
  }
</style>
